import axios from 'axios';
import _ from 'lodash';

const conf = {
  method: 'get',
  url: '/',
  baseURL: '',
  headers: {
    'content-type': 'application/x-www-form-urlencoded'
  },
  timeout: 100000
};
const defaultInstance = (config) => {
  const instance = axios.create(config);
  instance.interceptors.request.use((res) => res, (error) => { console.log(error); return false; });
  instance.interceptors.response.use((response) => response, (error) => {
    console.error(`接口:${error.config.url}  异常 --- ${error.message}`);
    if (!error.response) return false;
    console.error(error);
    return false;
  });
  return instance;
};
/**
 * 请求封装
 * @param {Object} opt 请求配置
 * @param {Object} data 参数
 * @param {Boolean} isLoading 加载动画
 * @param {Boolean} isEncode 是否编码
 */
export const http = async (config, data, instance = defaultInstance()) => {
  const setting = _.merge(conf, config);
  const { method } = setting;
  // eslint-disable-next-line no-unused-expressions
  method.toUpperCase() === 'GET' ? setting.params = data : setting.data = data;
  try {
    const res = await instance(setting);
    return res.data;
  } catch (error) {
    console.error(error);
    return { state: 0 };
  }
};

export default http;
